package com.example.starter.log.aspectj;

import com.example.starter.log.annotation.ApiLog;
import com.example.starter.log.publisher.ApiLogPublisher;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.util.StopWatch;

/**
 * @author 王令
 * @since 2023/4/14 16:05
 */
@Aspect
@ConditionalOnProperty(prefix = "com.example.log.api", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ApiLogAspectJ {

    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint point, ApiLog log) {
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            Object proceed = point.proceed();
            stopWatch.stop();
            ApiLogPublisher.publishEvent(log.module(), log.notes(), log.code(), stopWatch.getTotalTimeMillis());
            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

}
